const { ipcMain } = require('electron');

class VocabularyIPC {
  constructor(vocabularyService, learningProgressService, pronunciationService) {
    this.vocabularyService = vocabularyService;
    this.learningProgressService = learningProgressService;
    this.pronunciationService = pronunciationService;
    this.registerHandlers();
  }

  registerHandlers() {
    // Handle vocabulary search requests
    ipcMain.handle('vocabulary:search', async (event, pattern) => {
      try {
        const results = await this.vocabularyService.searchWords(pattern);
        return { success: true, data: results };
      } catch (error) {
        return { success: false, error: error.message };
      }
    });

    // Handle getting a specific word
    ipcMain.handle('vocabulary:get', async (event, word) => {
      try {
        console.log('IPC: Getting word:', word);
        const result = await this.vocabularyService.getWordByText(word);
        console.log('IPC: Got result:', result);
        return { success: true, data: result };
      } catch (error) {
        console.error('IPC: Error getting word:', error);
        return { success: false, error: error.message };
      }
    });

    // Handle getting words with pagination
    ipcMain.handle('vocabulary:list', async (event, { limit, offset }) => {
      try {
        const result = await this.vocabularyService.getWords(limit, offset);
        return {
          success: true,
          data: result.words,
          total: result.total,
        };
      } catch (error) {
        return { success: false, error: error.message };
      }
    });

    // Handle prefix search
    ipcMain.handle('vocabulary:search-prefix', async (event, { prefix, limit }) => {
      try {
        const results = await this.vocabularyService.searchWordsByPrefix(prefix, limit);
        return { success: true, data: results };
      } catch (error) {
        return { success: false, error: error.message };
      }
    });

    // Handle suffix search
    ipcMain.handle('vocabulary:search-suffix', async (event, { suffix, limit }) => {
      try {
        const results = await this.vocabularyService.searchWordsBySuffix(suffix, limit);
        return { success: true, data: results };
      } catch (error) {
        return { success: false, error: error.message };
      }
    });

    // Handle similar words search
    ipcMain.handle('vocabulary:search-similar', async (event, { word, limit }) => {
      try {
        const results = await this.vocabularyService.searchSimilarWords(word, limit);
        return { success: true, data: results };
      } catch (error) {
        return { success: false, error: error.message };
      }
    });

    // Handle adding to query history
    ipcMain.handle('vocabulary:add-history', async (event, word) => {
      try {
        const result = await this.vocabularyService.addQueryHistory(word);
        return { success: true, data: result };
      } catch (error) {
        return { success: false, error: error.message };
      }
    });

    // Handle getting query history
    ipcMain.handle('vocabulary:get-history', async (event, limit) => {
      try {
        const results = await this.vocabularyService.getQueryHistory(limit);
        return { success: true, data: results };
      } catch (error) {
        return { success: false, error: error.message };
      }
    });

    // Handle clearing query history
    ipcMain.handle('vocabulary:clear-history', async () => {
      try {
        const result = await this.vocabularyService.clearQueryHistory();
        return { success: true, data: result };
      } catch (error) {
        return { success: false, error: error.message };
      }
    });

    // Handle removing a single item from query history
    ipcMain.handle('vocabulary:remove-history-item', async (event, word) => {
      try {
        const result = await this.vocabularyService.removeQueryHistoryItem(word);
        return { success: true, data: result };
      } catch (error) {
        return { success: false, error: error.message };
      }
    });

    // Handle updating word's known status
    ipcMain.handle('vocabulary:update-known-status', async (event, { word, status }) => {
      try {
        const result = await this.vocabularyService.updateKnownStatus(word, status);
        return { success: true, data: result };
      } catch (error) {
        return { success: false, error: error.message };
      }
    });

    // Handle updating word's IELTS tag
    ipcMain.handle('vocabulary:update-ielts-tag', async (event, { word, tag }) => {
      try {
        const result = await this.vocabularyService.updateIeltsTag(word, tag);
        return { success: true, data: result };
      } catch (error) {
        return { success: false, error: error.message };
      }
    });

    // Handle getting learning statistics
    ipcMain.handle('learning-progress:get-statistics', async () => {
      try {
        const result = await this.learningProgressService.getLearningStatistics();
        return { success: true, data: result };
      } catch (error) {
        return { success: false, error: error.message };
      }
    });

    // Handle getting learning history
    ipcMain.handle('learning-progress:get-history', async (event, limit) => {
      try {
        const result = await this.learningProgressService.getLearningHistory(limit);
        return { success: true, data: result };
      } catch (error) {
        return { success: false, error: error.message };
      }
    });

    // Handle pronunciation playback
    ipcMain.handle('pronunciation:play', async (event, { audioPath }) => {
      try {
        console.log('Received pronunciation play request:', audioPath);

        // Process the audio path to handle escaped characters
        let processedAudioPath = audioPath;

        // Remove surrounding quotes if present
        if (processedAudioPath && processedAudioPath.startsWith('"') && processedAudioPath.endsWith('"')) {
          processedAudioPath = processedAudioPath.slice(1, -1);
        }

        // Fix escaped forward slashes
        if (processedAudioPath) {
          processedAudioPath = processedAudioPath.replace(/\\\//g, '/');
        }

        console.log('Processing audio playback for path:', processedAudioPath);

        // Verify that the audio file path is provided
        if (!processedAudioPath) {
          console.log('No audio path provided');
          return { success: false, error: 'No audio path provided' };
        }

        console.log('Calling pronunciation service to prepare audio');
        // For HTML5 audio, we just need to return the path
        const result = await this.pronunciationService.playPronunciation(processedAudioPath);
        console.log('Pronunciation service returned:', result);
        return result;
      } catch (error) {
        console.error('Error playing pronunciation:', error);
        return { success: false, error: error.message };
      }
    });

    // Handle pronunciation stop
    ipcMain.handle('pronunciation:stop', async () => {
      try {
        console.log('Received pronunciation stop request');
        const result = this.pronunciationService.stopPronunciation();
        return result;
      } catch (error) {
        console.error('Error stopping pronunciation:', error);
        return { success: false, error: error.message };
      }
    });
  }
}

module.exports = VocabularyIPC;
